package com.gu.weixinpaydemo.controller;

import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.Gu
 * @date 2020/1/11 14:53
 * @function :  查询微信支付订单
 **/
@CrossOrigin
@RestController
@RequestMapping("/query")
public class QueryOrder {

    @Autowired private HttpClient httpClient;

    @Value("${queryStatusUrl}")
    private String queryStatusUrl;

    @Value("${appid}")
    private String appid;

    @Value("${partner}")
    private String partner;

    @Value("${partnerkey}")
    private String partnerkey;

    @RequestMapping("/queryStatus")
    public Map queryStatus(String orderId) {

        //1.创建参数
        Map<String,String> param=new HashMap();//创建参数
        param.put("appid", appid);//公众号
        param.put("mch_id", partner);//商户号
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        param.put("out_trade_no", orderId);//订单号

        try {
            //生成要发送的xml
            String signedXml = WXPayUtil.generateSignedXml(param, partnerkey);

            String httpClientPost = httpClient.httpClientPost(signedXml, queryStatusUrl);

            //将放回的结果转换为map
            Map<String, String> map = WXPayUtil.xmlToMap(httpClientPost);

            //获得返回结果
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("return_code",map.get("return_code"));//返回状态码
            resultMap.put("return_msg",map.get("return_msg"));//返回信息
            resultMap.put("trade_state",map.get("trade_state"));//交易状态
            resultMap.put("trade_state_desc",map.get("trade_state_desc"));//交易状态描述

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}
